﻿CREATE PROCEDURE [dbo].[state__Action] 
	@ID int,
	@FromID int,
	@ToID int
AS
SET NOCOUNT ON

DECLARE @Action nvarchar(max)
DECLARE cur CURSOR LOCAL FOR
SELECT
CASE dbo.fs_IsStateFlowActionSP(StateFlowActionTypeID) WHEN 1 THEN 'EXEC ' ELSE '' END + StateFlowActionText
FROM v_StateFlow_Actions
WHERE(StateFromID = @FromID AND StateToID = @ToID  OR
			StateFromID IS NULL		AND StateToID = @ToID OR
			StateFromID = @FromID AND StateToID IS NULL
		 ) AND Priority > 0
ORDER BY Priority

OPEN cur

FETCH NEXT FROM cur INTO @Action

WHILE @@FETCH_STATUS = 0 BEGIN
	--EXEC sp__Trace '@ID:%s,@StatusFromID:%s,@StatusToID:%s,Action:%s',@ID,@FromID,@ToID,@Action
	--PRINT dbo.sprint4('@ID:%s,@StatusFromID:%s,@StatusToID:%s,Action:%s',@ID,@FromID,@ToID,@Action)
	EXEC sp_executesql @Action,N'@ID int OUTPUT,@StatusFromID int,@StatusToID int',@ID OUTPUT,@FromID,@ToID
	IF @@ERROR <> 0 BEGIN	/*IF @@TRANCOUNT > 0*/ ROLLBACK RETURN END
	IF @ID IS NULL BREAK
	FETCH NEXT FROM cur INTO @Action
END

CLOSE cur
DEALLOCATE cur

EXEC state_Loan_AssignGLProgram @ID
EXEC state_BatchArrivedMail @ID,@ToID
EXEC state_MailChildStatus @ID,@FromID,@ToID



